﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace EcologyFuture.DataCollection
{
  using EcologyFuture.Helper;
  /// <summary>
  /// <c>WeatherCoUaDataCollector</c> collects data from weather.co.ua.
  /// </summary>
  class WeatherCoUaDataCollector : IDataCollector
  {
    /// <summary>
    /// Collects data from weather.co.ua in xml format and converts it to <c>WeatherInfo</c>.
    /// </summary>
    /// <returns><c>WeatherInfo</c> struct with weather information from weather.co.ua.</returns>
    public WeatherInfo CollectData()
    {
      try
      {
        Stream xmlStream = WebHelper.GetDataFromUri("http://xml.weather.co.ua/1.2/forecast/17?dayf=1&lang=en");
        return GetWeather(xmlStream);
      }
      catch (Exception)
      {
        throw (new EFExeption("WeatherCoUa collection data exeption was throwed"));
      }
    }
    /// <summary>
    /// Converts weather info from WeatherCoUa xml format to internal <c>WeatherInfo</c> format.
    /// </summary>
    /// <param name="coUaXmlStream">Stream with xml data about the weather.</param>
    /// <returns>Weather information in <c>WeatherInfo</c> struct.</returns>
    WeatherInfo GetWeather(Stream coUaXmlStream)
    {
      WeatherInfo coUaWeather = new WeatherInfo();
      try
      {
        XmlReader reader = XmlReader.Create(coUaXmlStream);
        reader.ReadToFollowing("city");
        XmlReader city = reader.ReadSubtree();
        city.ReadToFollowing("name_en");
        coUaWeather.city = reader.ReadString();
        city.ReadToFollowing("country");
        XmlReader inner = reader.ReadSubtree();
        inner.ReadToFollowing("name_en");
        coUaWeather.country = reader.ReadString();
        reader.ReadToFollowing("current");
        inner = reader.ReadSubtree();
        inner.ReadToFollowing("time");
        coUaWeather.date = DateTimeHelper.ParseDate(reader.ReadString());
        inner.ReadToFollowing("t");
        coUaWeather.temperature = Convert.ToInt32(reader.ReadString());
        inner.ReadToFollowing("p");
        coUaWeather.pressure = Convert.ToSingle(reader.ReadString());
        inner.ReadToFollowing("w");
        coUaWeather.speed = Convert.ToSingle(reader.ReadString());
        inner.ReadToFollowing("w_rumb");
        coUaWeather.direction = Convert.ToInt32(reader.ReadString());
        inner.ReadToFollowing("h");
        coUaWeather.humidity = Convert.ToInt32(reader.ReadString());
      }
      catch (XmlException e)
      {
        Console.WriteLine("Xml exeption was throwed: " + e.Message);
        throw (new EFExeption());
      }
      catch (Exception e)
      {
        throw (new EFExeption("An exeption was throwed..." + e.Message));
      }
      return coUaWeather;
    }
  }
}
